﻿using System;
using System.Web;
using System.IO;

namespace Ehai.Web.Framework.Rules
{
    class DeleteRuleHandle : IMsgRuleHandle
    {
        #region IMsgRuleHandle 成员

#if DEBUG

        private int _execStatus = 0;
        public int ExecStatus
        {
            get { return _execStatus; }
        }

#endif
        public const string Name = "delete";


        #region  删除规则处理函数
        /// <summary>
        /// 从数据库删除一条记录，成功后会插入日志记录
        /// </summary>
        /// <param name="p">        
        /// 0:(必选)处理类型 delete<br/>
        /// 1:(必选)表名<br/>
        /// 2:(可选)条件,where子句的内容，但不包括where单词<br/>
        /// 3:(可选)要使用的连接字符串(id)(如果null或Empty，将按照以下顺序检索：标记为default的记录-->第一条记录<br/>
        /// </param>
        /// <param name="ci">环境变量ci</param>
        /// <example>示例代码</example>
        /// <code>
        /// string[] r = new string[4] { "delete", "ExampleTable", "id=3", "testdb" };
        /// Execute(r,ci);
        /// </code>
        /// <example>示例代码</example><code>
        /// string[] r = {"delete","DMMessge","MessageID=17","testdb2" };
        /// </code>
        /// <exception cref="Ehai.Web.Framework.WebException">
        /// Ehai.Web.Framework.WebException :删除记录或插入日志记录失败
        /// </exception>
        /// <returns>返回操作结果。[0][0]中的值代表操作结果,succeeded,failed</returns>
        public string[][] Execute(string[] p, ContextInfo ci)
        {
            if (p.Length < 2 || string.IsNullOrEmpty(p[1]))
            {

#if DEBUG
                _execStatus = -2;
#endif

                return null;
            }
            string sql_where = p.Length > 2 && !String.IsNullOrEmpty(p[2])? (" where " + p[2]) : string.Empty;
            string constrid = p.Length > 3 ? p[3] : null;

            try
            {
                int suc = -1;   //sql操作结果储存

                string sql = "delete from " + p[1] + sql_where;

                ApplicationDB DataBase = new ApplicationDB(sql, ci, constrid);

                string[][] result = { new String[] { String.Empty } }; //函数返回值变量

                suc = DataBase.ExecuteNonQuery();

                if (suc != -1)
                {
                    string Logsql = "insert into log(Msg,UserName,Ip,BrowserName,BrowserVersion,BrowserPlatform,operationTime)" +
                        "values('" + sql.Replace("'", "\\''").Replace("\"", "\\\"") + "','" + ci.Session["username"] + "','" + ci.Request.UserHostAddress +
                        "','" + ci.Request.Browser.Browser + "','" + ci.Request.Browser.Version + "','" +
                        ci.Request.Browser.Platform + "','" + DateTime.Now.ToString() + "')";

                    DataBase.Sql = Logsql;

                    int logResult = DataBase.ExecuteNonQuery();
                    if (logResult != 1)
                        throw new Exception("删除记录过程中写入日志出错,返回操作数：" + logResult);

                    result[0][0] = "succeeded";
                }
                else
                    result[0][0] = "failed";

#if DEBUG
                _execStatus = 0;
#endif

                return result;

            }
            catch (Exception ex)
            {
#if DEBUG
                _execStatus = -1;
#endif
                throw new Ehai.Web.Framework.WebException("Ehai.Web.Framework.Rules.DeleteRule", "删除记录或插入日志记录失败", ex);
            }
        }
        #endregion

        public string GetHelpInfo()
        {
            return "从数据库删除一条记录";
        }

        public string GetHelpDetail()
        {
            return "从数据库删除一条记录，成功后会插入日志记录。参数范例：{ delete, ExampleTable, id=3, testdb }";
        }

        public string[] GetParametersInfo()
        {
            string[] t = new string[4];
            t[0] = "[0]:(必选)处理类型 delete<br/>";
            t[1] = "[1]:(必选)表名<br/>";
            t[2] = "[2]:(可选)条件,where子句的内容，但不包括where单词<br/>";
            t[3] = "[3]:(可选)要使用的连接字符串(id)(如果null或Empty，将按照以下顺序检索：标记为default的记录-->第一条记录<br/";
            return t;
        }

        #endregion
    }
}
